const {
    SleepStageCalculator,
    BaseLengthQueue,
    MovingAverageFilter,
    FixedLengthQueue,
    EEGSleepFeatureCalculate
} = require('./EEGSleepFeatureCalculate');

// 调试：检查导入的模块
console.log('Imported modules:', {
    SleepStageCalculator,
    BaseLengthQueue,
    MovingAverageFilter,
    FixedLengthQueue,
    EEGSleepFeatureCalculate
});

// 睡眠阶段服务主类
class SleepStageServeMain {
    Fs = 50; // 采样率
    queLen = this.Fs * 10; // 队列长度（30秒数据，基于采样率计算，修正为通过this访问Fs）
    queStep = this.Fs * 1; // 清除步长（15秒数据，修正为通过this访问Fs）
    winSize = 5; // 移动平均窗口大小
    baseSize = 5; // 基准队列大小
    queue_data = null; // 延迟初始化
    queue_base = new BaseLengthQueue(this.baseSize); // 修正为通过this访问baseSize
    eegFeature = new EEGSleepFeatureCalculate();
    filter = new MovingAverageFilter(this.winSize); // 修正为通过this访问winSize
    sdtrBaseline = 0.6; // 基准SDTR值
    baseEvent = 0; // 基准事件标志
    calculator = new SleepStageCalculator();
    ind1 = 0.45; // 阈值参数1
    ind2 = 0.5;  // 阈值参数2
    ind3 = 0.70; // 阈值参数3

    // 初始化队列方法，改为箭头函数避免作用域问题，或者保持普通函数在调用时确保this指向正确
    initialize = () => {
        if (!this.queue_data) {
            if (!FixedLengthQueue) {
                throw new Error("FixedLengthQueue 未定义，请检查 EEGSleepFeatureCalculate.js 的导出");
            }
            this.queue_data = new FixedLengthQueue(this.queLen, this.queStep); // 修正为通过this访问queLen、queStep
        }
    };

    outPutSleepStage(EEGFp1) {
        this.initialize(); // 调用实例方法，确保通过this调用
        let sleepStage = -1;
        try {
            this.queue_data.enqueue(EEGFp1);

            if (this.queue_data.isFull()) {
                const eegData = this.queue_data.getQueue();
                // console.log(`EEG数据长度: ${eegData.length}`); // 调试：输出数据长度
                if (eegData.length <= 1) {
                    // console.warn("EEG数据长度不足，跳过处理");
                    return sleepStage;
                }
                const deltaPower = this.eegFeature.computePowerInBand(eegData, this.Fs, 0.4, 1.0);
                const thetaPower = this.eegFeature.computePowerInBand(eegData, this.Fs, 4.0, 8.0);
                const sdtrValue = deltaPower / (deltaPower + thetaPower);
                const sdtrMovValue = this.filter.addSample(sdtrValue);

                if (this.queue_base.isFullQueue() && this.baseEvent === 0) {
                    this.baseEvent = 1;
                    // console.log("sleepStage: ", "aaa");
                } else if (this.baseEvent === 0) {
                    this.sdtrBaseline = this.queue_base.addAndComputeMean(sdtrValue, 3);
                    // console.log("sdtrBaseline: ", sdtrBaseline);
                }

                if (this.baseEvent === 1) {
                    sleepStage = this.calculator.calculateSleepStage(
                        this.sdtrBaseline,
                        sdtrMovValue,
                        this.ind1,
                        this.ind2,
                        this.ind3
                    );
                    // console.log("sleepStage: ", sleepStage);
                }
            }
        } catch (error) {
            console.error("outPutSleepStage错误: ", error);
        }
        return sleepStage;
    }
}

module.exports = { SleepStageServeMain };